package top.xtcoder.jdcbase.test.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.docx4j.dml.chart.SerContent;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.ReactiveExtensionAwareQueryMethodEvaluationContextProvider;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import top.xtcoder.jdcbase.base.core.Resp;
import top.xtcoder.jdcbase.rbac.entity.AdminInfo;

@Controller
@RequestMapping
public class IndexController {
    @Autowired
    private Dao dao;

    @GetMapping("/index.json")
    @ResponseBody
    public Resp index() {
        return Resp.OK("index");
    }
    
    private String secret = new String(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
    @PostMapping("/aesApi")
    @ResponseBody
    public Resp aesApi(@RequestBody AdminInfo data, HttpServletRequest req) {
    	System.out.println("body数据=" + Json.toJson(data));
    	System.out.println("密钥： " + secret);
    	byte[] key = secret.getBytes();
    	SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
    	
    	String sign = req.getHeader("sign");
    	System.out.println("====>" + sign);
    	//解密为字符串
    	String decryptStr = aes.decryptStr(sign, CharsetUtil.CHARSET_UTF_8);
    	System.out.println("解密出的字符串=" + decryptStr);
    	
        return Resp.OK("index");
    }
    
    @GetMapping("/aesApiClientTest")
    @ResponseBody
    public Resp aesApiClientTest() {
    	AdminInfo data = new AdminInfo(); //随便传一个数据测试
    	data.init();
    	data.setAccount("admin");

    	System.out.println("密钥： " + secret);
    	byte[] key = secret.getBytes();
    	
    	SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

    	String content = "param1=001&param2=002&timestamp=" + System.currentTimeMillis(); //加密参数,可以放数据量少的参数，数据量大的参数比如成绩可以放到body里
    	//加密为16进制表示
    	String sign = aes.encryptHex(content);
    	String url = "http://localhost:4477/aesApi?&sign=" + sign;
    	String body = Json.toJson(data);
    	int timeout = 60_000;
    	
    	HttpRequest req = HttpUtil.createPost(url);
    	req.body(body);
    	req.header("sign", sign);
    	req.timeout(timeout);
    	String resp = req.execute().body();
        return Resp.OK("接口调用结果").data(resp);
    }
}
